package cn.itsource.utils;

import cn.itsource.hbc.org.domain.Employee;
import cn.itsource.hbc.org.service.IEmployeeService;
import cn.itsource.hbc.user.domain.LoginInfo;
import cn.itsource.hbc.user.domain.User;
import cn.itsource.hbc.user.service.IUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

public class LoginContext {

    // 返回当前登录用户user、emp
    public static Object getCurrent(HttpServletRequest request){

        // 通过request对象获取加入请求头中的token
        String token = request.getHeader("TOKEN");
        System.out.println(token);
        // 获取spring管理的bean对象
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        // 从容器中拿出想要的对象getBean方法
        RedisTemplate redisTemplate = applicationContext.getBean("redisTemplate", RedisTemplate.class);
        // 获取到用户登录信息
         LoginInfo loginInfo= (LoginInfo)redisTemplate.opsForValue().get(token);
        // 通过loginInfo对象判断用户性质1代表前端0代表后端
        System.out.println(loginInfo);
        if (loginInfo.getType()==1){
            IUserService userService = applicationContext.getBean(IUserService.class);
            User user = userService.loadById(loginInfo.getUId());
            return user;

        }else {
            IEmployeeService employeeService = applicationContext.getBean( IEmployeeService.class);
            Employee employee = employeeService.loadById(loginInfo.getUId());
            return employee;
        }

    }

}
